﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using WbsEditor.Properties;
using System.Diagnostics;
using System.Security.Principal;

namespace WbsEditor
{
    public static class ProtocolSetup
    {
        private static string ApplicationPath
        {
            get
            {
                return Path.Combine(Application.StartupPath, "wbseditor.exe");
            }
        }
        private static bool IsSetupRequired
        {
            get
            {
                return !IsProtocolRegistered && UserWantsProtocol;
            }
        }
        private static bool UserWantsProtocol
        {
            get
            {
                return !Settings.Default.SuppressWBSProtocolRegistration;
            }
        }
        private static bool IsUserAdmin
        {
            get
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
        }

        public static bool IsProtocolRegistered
        {
            get
            {
                return String.Equals(ApplicationPath, Settings.Default.WBSProtocolTarget, StringComparison.OrdinalIgnoreCase);
            }
        }

        public static void AutoUpdate()
        {
            if (!IsSetupRequired)
                return;

            Register();
        }

        public static void Register()
        {
            if (!IsUserAdmin)
                MessageBox.Show("Now registering wbsedit Protocol");

            string regKeyContent =
@"Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\wbsedit]
""URL Protocol""=""""
@=""URL:WBS Editor Root""

[HKEY_CLASSES_ROOT\wbsedit\shell]
[HKEY_CLASSES_ROOT\wbsedit\shell\open]

[HKEY_CLASSES_ROOT\wbsedit\shell\open\command]
@=""\""{0}\"" \""%1\""""
";
            string value = String.Format(regKeyContent, ApplicationPath.Replace("\\", "\\\\"));
            try
            {
                ApplyRegValue(value);

                Settings.Default.WBSProtocolTarget = ApplicationPath;
                Settings.Default.SuppressWBSProtocolRegistration = false;
            }
            catch (Exception ex)
            {
                if (MessageBox.Show(String.Format("Error registering wbsedit protocol: {0}\r\n\r\nSuppress further notifications?", ex.Message), "Error registering protocol", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
                    Settings.Default.SuppressWBSProtocolRegistration = true;
            }
        }
        public static void Unregister()
        {
            if (!IsUserAdmin)
                MessageBox.Show("Now unregistering wbsedit protocol");

            string regKeyContent =
@"Windows Registry Editor Version 5.00

[-HKEY_CLASSES_ROOT\wbsedit]";

            try
            {
                ApplyRegValue(regKeyContent);

                Settings.Default.WBSProtocolTarget = String.Empty;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error unregistering wbsedit protocol " + ex.Message);
            }

            Settings.Default.SuppressWBSProtocolRegistration = true;
        }

        private static void ApplyRegValue(string regValue)
        {
            string tempFile = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetRandomFileName(), ".reg"));
            File.WriteAllText(tempFile, regValue);

            try
            {
                Process p = Process.Start("regedit", String.Format("/s \"{0}\"", tempFile));
                p.WaitForExit();

                if (p.ExitCode != 0)
                    throw new Exception("Process exited with code " + p.ExitCode);
            }
            finally
            {
                File.Delete(tempFile);
            }
        }
    }
}
